package com.gitee.huxing.course.netty.threadpool;

import java.util.concurrent.*;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.netty.threadpool
 * @ClassName: ThreadPool
 * @Author: huxing
 * @DateTime: 2021-08-23 上午10:38
 */
public class ThreadPool {

    /** 线程池核心大小数 **/
    private static final int corePoolSize = Runtime.getRuntime().availableProcessors();

    /** 最大线程数 **/
    private static final  int maximumPoolSize = corePoolSize * 10;

    /** 超过corePoolSize的线程多久不活动被销毁时间 **/
    private static final long keepAliveTime = 30L ;

    /** 时间单位 **/
    private static final TimeUnit unit = TimeUnit.SECONDS;

    /** 任务队列 **/
    private static BlockingQueue<Runnable> workQueue = new SynchronousQueue<>();

    /** 自定义服务端线程池 **/
    private Executor serverExecutor;

    /** 自定义网关线程池 **/
    private Executor gatewayExecutor;

    /** 静态对象 **/
    public static ThreadPool instance = new ThreadPool();

    /**
     * @Description: 双重检索创建一个静态对象
     * @Author: huxing
     * @param
     * @return com.gitee.huxing.course.netty.threadpool.ThreadPool
     * @Date: 2021/8/23 上午10:42
     **/
    public static ThreadPool getInstance(){
        if (instance == null){
            instance = new ThreadPool();
        }
        return instance;
    }

    public ThreadPool(){
       this.serverExecutor = builder();
       this.gatewayExecutor = builder();
    }

//    /**
//     * @Description: 创建一个线程池
//     * @Author: huxing
//     * @param
//     * @Date: 2021/8/23 上午10:43
//     **/
//    public Executor builder(){
//        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
//                keepAliveTime, unit, workQueue);
//    }

    /**
     * @Description: 创建一个线程池
     * @Author: huxing
     * @param
     * @Date: 2021/8/23 上午10:43
     **/
    public Executor builder(){
        return Executors.newCachedThreadPool();
    }

    /**
     * @Description: 根据类型获取当前使用的线程池
     * @Author: huxing
     * @param type
     * @return java.util.concurrent.Executor
     * @Date: 2021/8/23 上午11:08
     **/
    public Executor getExecutor(int type) {
        return (type == 1) ? serverExecutor : gatewayExecutor;
    }
}
